package com.desiremall.util;

import java.io.IOException;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



public class MyBatisUtil {
	// 因为它要始终存在，静态的属于类的，只初始化一次
	public static SqlSessionFactory factory =null;
	static{
		String resource = "mybatis-config.xml";
		//获取mybatis-config.xml文件的输入流
		try {
			InputStream is = Resources.getResourceAsStream(resource);
			//创建SqlSessionFactory对象，此对象可以完成对配置文件的读取
			factory = new SqlSessionFactoryBuilder().build(is);
		    
		} catch (IOException e) {
			
			e.printStackTrace();
		}
	
	}
	
	/**
	 * 获取连接
	 * @return
	 */
	public static SqlSession getSession(){
		//true 自动提交
		//false 手动提交
		return factory.openSession(false);
	}
	
	/**
	 * 
	 * @param sqlSession 引用传递，给我对象，我帮你关闭
	 */
	public static void closeSqlSession(SqlSession sqlSession){
		if(null!=sqlSession){
		  sqlSession.close();
		}
	}
}
